<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  
  <title>synchronized分析篇 | JAVA</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="Synchronized">
  
  
  
  
  <meta name="description" content="Synchronized 非静态方法锁的是当前对象（this） 静态方法锁的类对象Test.class 代码块锁的是自定义的Object对象  示例代码 123456789101112131415161718192021public class Test &amp;#123;    //对象    Object object=new Object();    //共享变量    private stati">
<meta name="keywords" content="Synchronized">
<meta property="og:type" content="article">
<meta property="og:title" content="Synchronized分析篇">
<meta property="og:url" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/index.html">
<meta property="og:site_name" content="JAVA">
<meta property="og:description" content="Synchronized 非静态方法锁的是当前对象（this） 静态方法锁的类对象Test.class 代码块锁的是自定义的Object对象  示例代码 123456789101112131415161718192021public class Test &amp;#123;    //对象    Object object=new Object();    //共享变量    private stati">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/20210121211040.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/640.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/monitor.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121210220837.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121201536929.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121201843560.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121203245241.png">
<meta property="og:updated_time" content="2021-01-23T01:54:04.868Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Synchronized分析篇">
<meta name="twitter:description" content="Synchronized 非静态方法锁的是当前对象（this） 静态方法锁的类对象Test.class 代码块锁的是自定义的Object对象  示例代码 123456789101112131415161718192021public class Test &amp;#123;    //对象    Object object=new Object();    //共享变量    private stati">
<meta name="twitter:image" content="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/20210121211040.png">
  
    <link rel="alternate" href="/atom.xml" title="JAVA" type="application/atom+xml">
  

  

  <link rel="icon" href="/css/images/mylogo.jpg">
  <link rel="apple-touch-icon" href="/css/images/mylogo.jpg">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt; src:url("/css/fonts/FuturaPTBold.otf") format("woff");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt-light; src:url("/css/fonts/FuturaPTBook.otf") format("woff");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt-italic; src:url("/css/fonts/FuturaPTBookOblique.otf") format("woff");font-weight:400;font-style:italic;}
}

  </style>
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>
  <script src="/js/bootstrap.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css">

  
    <link rel="stylesheet" href="/css/dialog.css">
  

  

  
    <link rel="stylesheet" href="/css/header-post.css">
  

  
  
  
    <link rel="stylesheet" href="/css/vdonate.css">
  

</head>
</html>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  
  <div id="container">
    <div id="wrap">
      
        <header>

    <div id="allheader" class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-inner">
          
          <div class="container"> 
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>

            
              <a class="brand" style="border-width: 0;">
                <p>JAVA</p>
              </a>
            
            
            <div class="navbar-collapse collapse">
              <ul class="hnav navbar-nav">
                
                  <li> <a class="main-nav-link" href="/">首页</a> </li>
                
                  <li> <a class="main-nav-link" href="/archives">归档</a> </li>
                
                  <li> <a class="main-nav-link" href="/categories">分类</a> </li>
                
                  <li> <a class="main-nav-link" href="/tags">标签</a> </li>
                
                  <li> <a class="main-nav-link" href="/about">关于</a> </li>
                
                  <li><div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder>
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词...">
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(无标题)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div></li>
            </ul></div>
          </div>
                
      </div>
    </div>

</header>



      
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Synchronized分析篇" style="width: 75%; float:left;" class="article article-type-post" itemscope itemprop="blogPost">
  <div id="articleInner" class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" itemprop="name">
      Synchronized分析篇
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	<a href="/2020/12/28/Synchronized分析篇/" class="article-date">
	  <time datetime="2020-12-28T12:24:22.000Z" itemprop="datePublished">2020-12-28</time>
	</a>

      
    <a class="article-category-link" href="/categories/并发编程/">并发编程</a>

      
	<a class="article-views">
	<span id="busuanzi_container_page_pv">
		阅读量<span id="busuanzi_value_page_pv"></span>
	</span>
	</a>

      

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="Synchronized"><a href="#Synchronized" class="headerlink" title="Synchronized"></a>Synchronized</h2><ul>
<li>非静态方法锁的是当前对象（this）</li>
<li>静态方法锁的类对象Test.class</li>
<li>代码块锁的是自定义的Object对象</li>
</ul>
<p><strong>示例代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="comment">//对象</span></span><br><span class="line">    Object object=<span class="keyword">new</span> Object();</span><br><span class="line">    <span class="comment">//共享变量</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> num;</span><br><span class="line">    <span class="comment">//静态方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">lock1</span><span class="params">()</span></span>&#123;</span><br><span class="line">        num ++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//普通方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span>  <span class="keyword">void</span> <span class="title">lock2</span><span class="params">()</span></span>&#123;</span><br><span class="line">        num ++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">lock3</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//代码块</span></span><br><span class="line">        <span class="keyword">synchronized</span> (object)&#123;</span><br><span class="line">            num ++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>把Test.java编译成Test.class,并在对应目录下执行javap -v Test.class这个命令，可以看到对应的字节码</p>
<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/20210121211040.png" alt="img" style="zoom: 67%;">

<p>上面可以看到JVM对于同步方法和同步代码块的处理方式是不通的</p>
<p><strong>对于同步代码块</strong>：采用 monitorenter 和 monitorexit 两个指令来实现同步。</p>
<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/640.png" alt="img" style="zoom:67%;">

<p>进入monitorenter指令后，线程将持有Monitor对象，退出monitorexit指令后，线程将释放该Monitor对象。</p>
<p><strong>对于方法</strong>：出现了ACC_SYNCHRONIZED 标识。</p>
<p>当出现了 ACC_SYNCHRONIZED 标识符的时候，Jvm 会隐式调用 monitorenter 和 monitorexit。在执行同步方法前会调用 monitorenter，在执行完同步方法后会调用 monitorexit，释放 Monitor 对象。</p>
<p>你可以发现，不管是同步代码块还是同步方法，都和 <strong>Monitor</strong> 对象有关系。</p>
<p>ObjectMonitor主要数据结构</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">ObjectMonitor() &#123;</span><br><span class="line">    _header       = NULL;</span><br><span class="line">    _count        = <span class="number">0</span>;</span><br><span class="line">    _waiters      = <span class="number">0</span>,</span><br><span class="line">    _recursions   = <span class="number">0</span>;     <span class="comment">//线程的重入次数</span></span><br><span class="line">    _object       = NULL;  <span class="comment">//存储该monitor对象</span></span><br><span class="line">    _owner        = NULL;  <span class="comment">//标识拥有该monitor的线程</span></span><br><span class="line">    _WaitSet      = NULL;  <span class="comment">//处于wait状态的线程会被加入到_WaitSet</span></span><br><span class="line">    _WaitSetLock  = <span class="number">0</span> ;</span><br><span class="line">    _Responsible  = NULL ;</span><br><span class="line">    _succ         = NULL ;</span><br><span class="line">    _cxq          = NULL ; <span class="comment">//多线程竞争锁时的单向列表</span></span><br><span class="line">    FreeNext      = NULL ;</span><br><span class="line">    _EntryList    = NULL ; <span class="comment">//等待获取锁的线程，会放到这里</span></span><br><span class="line">    _SpinFreq     = <span class="number">0</span> ;</span><br><span class="line">    _SpinClock    = <span class="number">0</span> ;</span><br><span class="line">    OwnerIsThread = <span class="number">0</span> ;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/monitor.png" alt="image-20201216100004410" style="zoom:80%;">

<p>可以看到ObjectMonitor的数据结构中包含：<strong>_owner</strong>、_<strong>WaitSet</strong> 和<strong>_EntryList</strong></p>
<p>他们之间的关系转换如下</p>
<ol>
<li>当多线程同时访问同一代码块或者某个同步方法的时候，这些线程会首先被放进EntryList队里中，处于blocked状态线程都会放入该队里。</li>
<li>当某个线程获取对象的Monitor时，此时就可以进入running状态，执行代码逻辑，此时Monitor对象owner指向当前线程，count+1表示当前对象锁被一个线程获取，而没有获取锁的线程，会再次进入EntryList被挂起。</li>
<li>当running状态调用wait()方法当前就会释放Monitor对象，进入waiting状态，Monitor对象owner变成null,count减1,同时线程进入waitSet队列，直到有线程调用notify()方法唤醒该线程，则线程再次进入EntryList队列，直到再次竞争到锁再进入owner区。</li>
<li>如果当前线程执行完毕，那么也释放monitor对象，Monitor对象的owner变为null,count减1。</li>
</ol>
<p>JDK6之前，synchronized关键字的效率是很低的。</p>
<p>原因如下：</p>
<p>Monitor对象是依赖底层操作系统的Mutex Lock来实现互斥的，线程申请Mutex成功，则持有该Mutex,其他线程将无法获取到该Mutex。</p>
<blockquote>
<p>Mutex Lock涉及到底层操作系统，那这个时候就存在操作系统用户态和内核态的转换，这种切换会消耗大量系统资源，因为用户态与内核态都有各自专用的内存空间，专用的寄存器等。用户态切换至内核态需要传递给许多变量、参数给内核、内核也需要保护好用户态在切换时的一些寄存器值、变量等。</p>
</blockquote>
<p>所以JDK6之后，从jvm层面进行了优化，分为<strong>偏向锁，轻量级锁，自旋锁，重量级锁</strong>。</p>
<h2 id="锁升级"><a href="#锁升级" class="headerlink" title="锁升级"></a>锁升级</h2><p><strong>对象头Mark Work空间</strong></p>
<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121210220837.png" alt="image-20210121210220837" style="zoom:80%;">

<h3 id="偏向锁"><a href="#偏向锁" class="headerlink" title="偏向锁"></a>偏向锁</h3><p>HotSpot作者经过研究实践发现，在大多数情况下，锁不仅不存在多线程竞争，而且总是由同一线程多次获得，为了让线程获得锁的代价更低，引进了偏向锁。</p>
<p>偏向锁,它的意思是<strong>这个锁会偏向于第一个获得他的线程，会在对象头存储锁偏向的线程ID，以后线程进入和退出同步块时只需要检查是否为偏向锁，锁标识位以及ThreadID即可。</strong></p>
<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121201536929.png" alt="image-20210121201536929" style="zoom:80%;">

<p>无锁到偏向锁的转换流程图</p>
<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121201843560.png" alt="image-20210121201843560" style="zoom:80%;">

<p>   默认开启，参数设置：-XX:+UseBiasedLocking开启偏向锁</p>
<p><strong>简单流程：</strong></p>
<ol>
<li>线程访问同步代码块，使用CAS操作将ThreadID放到MarkWord当中</li>
<li>如果线程CAS成功，此线程获取到偏向锁。</li>
<li>如果线程CAS失败，证明已经有别的线程持有锁，这个时候启动偏向锁撤销</li>
</ol>
<p><strong>偏向锁的撤销</strong></p>
<ol>
<li>偏向锁的撤销动作必须等待全局安全点。</li>
<li>暂停原持有偏向锁的线程</li>
<li>将ThreadID设置为Null，使其变成无锁状态。</li>
<li>恢复持有偏向锁线程，开始进行轻量级加锁流程。</li>
</ol>
<h3 id="轻量级锁"><a href="#轻量级锁" class="headerlink" title="轻量级锁"></a>轻量级锁</h3><p>引入轻量级锁的目的：在多线程<strong>交替执行</strong>同步块的情况下，尽量避免重量级锁引起的性能消耗，但是如果多个线程在同一时刻进入临界区，会导致轻量级锁膨胀升级重量级锁，所以轻量级锁的出现并不是要代替重量级锁。</p>
<p>流程图如下:</p>
<img src="https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/image-20210121203245241.png" alt="image-20210121203245241" style="zoom:80%;">

<ol>
<li>判断当前对象是否处于无锁状态（hashcode、0、01），如果是，则JVM首先将在当前线程的栈帧中建立一个名为锁记录（Lock Record）的空间，用于存储锁对象目前的Mark Work的拷贝（官方把这份拷贝加了一个Displaced前缀，即Displaced Mark Work）,将对象的Mark Work复制到栈帧中的Lock Record中，将Lock Record中的owner指向当前对象。</li>
<li>JVM利用CAS操作尝试将对象的Mark Work更新指向Lock Record的指针，如果成功，表示竞争到锁，则将锁标志位变为00，执行同步。</li>
<li>如果失败，则判断当前对象的Mark Work是否指向当前线程的栈帧，如果是，则表示当前线程已经持有当前对象锁，则直接执行同步代码块;否则只能说明该锁对象已经被其他线程占用了，这时轻量级锁需要膨胀为重量级锁，锁标识位变为10，后面等到的线程将会进入阻塞状态。</li>
</ol>
<h3 id="自旋锁"><a href="#自旋锁" class="headerlink" title="自旋锁"></a>自旋锁</h3><p>前面聊 monitor 实现锁的时候，知道 monitor 会阻塞和唤醒线程，线程的阻塞和唤醒需要 CPU 从用户态转为核心态，频繁的阻塞和唤醒对 CPU 来说是一件负担很重的工作，这些操作给系统的并发性能带来了很大的压力。</p>
<p>同时，虚拟机的开发团队也注意到在许多应用上，共享数据的锁定状态只会持续很短的一段时间，为了这段时间阻塞和唤醒线程并不值得。</p>
<p>如果物理机器有一个以上的处理器，能让两个或以上的线程同时并行执行，我们就可以让后面请求锁的那个线程“稍等一下”，但不放弃处理器的执行时间，看看持有锁的线程是否很快就会释放锁。为了让线程等待，我们只需让线程执行一个循环(自旋) , 这就是所谓的<strong>自旋锁</strong>。</p>
<p><strong>自旋锁的优缺点</strong></p>
<p>自旋等待不能代替阻塞，且先不说对处理器数量的要求，自旋等待本身虽然避免了线程切换的开销，但它是要占用处理器时间的。</p>
<p>如果锁被占用的时间很短，自旋等待的效果就会非常好，反之，如果锁被占用的时间很长。那么自旋的线程只会白白消耗处理器资源，而不会做任何有用的工作，反而会带来性能上的浪费。</p>
<p>所以，自旋等待的时间必须要有一定的限度，如果在多线程交替执行同步块的情况下，可以避免重量级锁引起的性能消耗。</p>
<p>自旋超过了限定的次数仍然没有成功获得锁，就应当使用传统的方式去挂起线程了。自旋次数的默认值是10次，你可以使用参数 <strong>-XX : PreBlockSpin</strong> 来更改。</p>
<h3 id="适应性自旋锁"><a href="#适应性自旋锁" class="headerlink" title="适应性自旋锁"></a>适应性自旋锁</h3><p>在JDK 6中引入了自适应的自旋锁。自适应意味着自旋的时间不再固定了，而是由前一次在同一锁上的自选时间及锁的拥有者的状态来决定。</p>
<p>如果在同一个对象锁上，自旋等待刚刚成功获得过锁，并且持有锁的线程正在运行中，那虚拟机就会认为这次自旋也很有可能再次成功，进而它将允许自旋等待持续相对更长的时间，比如100次循环。</p>
<p>如果，对于某个锁，自旋很少成功获得过，那在以后要获取这个锁时可能会省略掉自旋过程，避免浪费服务器处理资源。</p>

      
    </div>
    <footer class="article-footer">
      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: '打赏支持', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://raw.githubusercontent.com/iTimeTraveler/iTimeTraveler.github.io/site/source/about/donate/images/WeChanQR.png',
  alipayImage: 'https://raw.githubusercontent.com/iTimeTraveler/iTimeTraveler.github.io/site/source/about/donate/images/AliPayQR.jpg'
});
</script>
      
      
      <div>
        <ul class="post-copyright">
          <li class="post-copyright-author">
          <strong>本文作者:  </strong>LeBron Tao
          </li>
          <li class="post-copyright-link">
          <strong>本文链接:  </strong>
          <a href="/2020/12/28/Synchronized分析篇/" target="_blank" title="Synchronized分析篇">https://jameslin23.gitee.io/2020/12/28/Synchronized分析篇/</a>
          </li>
          <li class="post-copyright-license">
            <strong>版权声明:   </strong>
            本博客所有文章除特别声明外，均采用 <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-ND 4.0</a>
            许可协议。转载请注明出处
          </li>
         
        </ul>
<div>
</div></div>
      
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8yOTQ4MS82MDQ5">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>



      
      
        
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Synchronized/">Synchronized</a></li></ul>

      

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/12/30/JVM篇之标记清除算法/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          JVM篇之标记清除算法
        
      </div>
    </a>
  
  
    <a href="/2020/12/28/AQS源码分析/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">AQS源码分析</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="toc-sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    
        <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Synchronized"><span class="nav-number">1.</span> <span class="nav-text">Synchronized</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#锁升级"><span class="nav-number">2.</span> <span class="nav-text">锁升级</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#偏向锁"><span class="nav-number">2.1.</span> <span class="nav-text">偏向锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#轻量级锁"><span class="nav-number">2.2.</span> <span class="nav-text">轻量级锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自旋锁"><span class="nav-number">2.3.</span> <span class="nav-text">自旋锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#适应性自旋锁"><span class="nav-number">2.4.</span> <span class="nav-text">适应性自旋锁</span></a></li></ol></li></ol>
    
    </div>
  </aside>

</section>
        
      </div>
      
      <footer id="footer">
  

  <div class="container">
      	<div class="row">
	      <p> Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> and <a href="https://github.com/iTimeTraveler/hexo-theme-hiker" target="_blank">Hexo-theme-hiker</a> </p>
	      <p id="copyRightEn">Copyright &copy; 2013 - 2021 JAVA All Rights Reserved.</p>
	      
	      
    		<p class="busuanzi_uv">
				访客数 : <span id="busuanzi_value_site_uv"></span> |  
				访问量 : <span id="busuanzi_value_site_pv"></span>
		    </p>
  		   
		</div>

		
  </div>
</footer>


<!-- min height -->

<script>
    var wrapdiv = document.getElementById("wrap");
    var contentdiv = document.getElementById("content");
    var allheader = document.getElementById("allheader");

    wrapdiv.style.minHeight = document.body.offsetHeight + "px";
    if (allheader != null) {
      contentdiv.style.minHeight = document.body.offsetHeight - allheader.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    } else {
      contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    }
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>




  <script src="/js/dialog.js"></script>








	<div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2 class="modal-title" id="myModalLabel">设置</h2>
      </div>
      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">


      <div class="modal-body">
          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" onclick="javascript:setFontSize();" aria-expanded="true" aria-controls="collapseOne">
              正文字号大小
            </a>
          </div>
          <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            您已调整页面字体大小
          </div>
        </div>
      


          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" onclick="javascript:setBackground();" aria-expanded="true" aria-controls="collapseTwo">
              夜间护眼模式
            </a>
        </div>
          <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
          <div class="panel-body">
            夜间模式已经开启，再次单击按钮即可关闭 
          </div>
        </div>

        <div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关 于&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
        </div>
         <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
          <div class="panel-body">
            JAVA
          </div>
          <div class="panel-body">
            Copyright © 2021 LeBron Tao All Rights Reserved.
          </div>
        </div>
      </div>


      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
    </div>
  </div>
</div>
  
  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
  
    <a id="menu-switch"><i class="fa fa-bars fa-lg"></i></a>
  
</body>
</html>